package cglibProxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @Author Yenchingcheng
 * @Date 2023/6/13 21:00
 * @Description
 **/
public class CglibProxy implements MethodInterceptor {
    private Enhancer enhancer=new Enhancer();

    private Object target;

    public CglibProxy(Object target) {
        this.target = target;
    }

    public Object getProxy(){
        //设置需要创建子类的类
        enhancer.setSuperclass(target.getClass());
        enhancer.setCallback(this);
        return enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        String name = method.getName();
        System.out.println("这是通过Cglib生成的:");
        if(name.equals("sleep")){
            System.out.println("good night.");
        }else if(name.equals("wakeUp")){
            System.out.println("good morning.");
        }
        return method.invoke(target,objects);
    }
}
